package com.foogui.service.impl;

import com.foogui.api.OrderFeignClient;
import com.foogui.api.StockFeignClient;
import com.foogui.dto.CommodityDTO;
import com.foogui.dto.OrderDTO;
import com.foogui.dubbo.OrderDubboService;
import com.foogui.dubbo.StockDubboService;
import com.foogui.service.MallService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
@RefreshScope
public class MallServiceImpl implements MallService {
    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private StockFeignClient stockFeignClient;

    @DubboReference(check = false)
    private OrderDubboService orderDubboService;

    @DubboReference(check = false)
    private StockDubboService stockDubboService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${switch.purchase.rollback}")
    private Boolean rollback = Boolean.FALSE;

    @GlobalTransactional
    public void purchase(String userId, String commodityCode, Integer count) {
        log.info("开始全局事务，XID = " + RootContext.getXID());

        stockFeignClient.deduct(commodityCode, count);

        orderFeignClient.create(userId, commodityCode, count);

        if (rollback) {
            throw new RuntimeException("账户或库存不足，执行回滚");
        }

        // 向mq中投递一个下单成功的消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("commodityCode", commodityCode);
        map.put("count", count);
        rocketMQTemplate.convertAndSend("order-topic", map);

        log.info("全局事务结束，XID = " + RootContext.getXID());
    }

    @GlobalTransactional
    public void purchaseOfDubbo (String userId, String commodityCode, Integer count) {
        log.info("Dubbo服务-开始全局事务，XID = " + RootContext.getXID());
        //1、扣减库存
        CommodityDTO commodityDTO = new CommodityDTO();
        commodityDTO.setCommodityCode(commodityCode);
        commodityDTO.setCount(count);
        stockDubboService.reduce(commodityDTO);
        //2、创建订单
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUserId(userId);
        orderDTO.setCommodityCode(commodityCode);
        orderDTO.setOrderCount(count);
        orderDubboService.create(orderDTO);
        log.info("Dubbo服务-全局事务结束，XID = " + RootContext.getXID());
    }
}
